let logger = require("pomelo-logger").getLogger(__filename);
let headlineLoader = require("../entities/headline").loadFromDocument;
let headlineCreator = require("../entities/headline").create;
let DateUtil = require("../../utils/dateUtil");

let HeadlineService = function (app) {
    this.app = app;
    this.headlines = [];
    this.nextHeadlineId = 0;
};

HeadlineService.prototype.initialize = function () {
    logger.info(`HeadlineService initialize...`);
    let headlineDao = this.app.get("headlineDao");
    headlineDao.findAllHeadlines(documents => {
        for(let document of documents) {
            let headline = headlineLoader(document);
            logger.info(`findAllHeadlines headline ${JSON.stringify(headline)}`);
            this.headlines.push(headline);
            if (headline.id >= this.nextHeadlineId) {
                this.nextHeadlineId = headline.id + 1;
            }
        }
        setInterval(() => this.tick(), 60 * 1000);
    });
};

HeadlineService.prototype.addHeadline = function (content, startTime, endTime, frequency, callback) {
    let headlineDao = this.app.get("headlineDao");
    let now = DateUtil.nowMS();
    let headline = headlineCreator(this.nextHeadlineId, content, startTime, endTime, frequency, now);
    this.nextHeadlineId = this.nextHeadlineId + 1;
    headlineDao.addHeadline(headline.toBSON(), result => {
        if(!result || result.result.ok != 1) {
            callback(null);
            return;
        }
        this.headlines.push(headline);
        callback(headline);
    });
};

HeadlineService.prototype.updateHeadline = function (id, content, startTime, endTime, frequency, callback) {
    let headlineDao = this.app.get("headlineDao");
    headlineDao.updateHeadline(id, content, startTime, endTime, frequency, result => {
        if(!result || result.result.ok != 1) {
            callback(null);
            return;
        }
        for(let item of this.headlines) {
            if(item.id === id) {
                item.content = content;
                item.startTime = startTime;
                item.endTime = endTime;
                item.frequency = frequency;
                item.lastTick = 0;
                callback(item);
                return;
            }
        }
        callback(null);
    });
};

HeadlineService.prototype.findAllHeadlines = function (callback) {
    let headlineDao = this.app.get("headlineDao");
    headlineDao.findAllHeadlines(documents => {
        if(!documents) {
            callback([]);
            return;
        }
        let headlines = [];
        for(let document of documents) {
            let headline = headlineLoader(document);
            headlines.push(headline);
        }
        callback(headlines);
    });
};

HeadlineService.prototype.findHeadlineById = function (id, callback) {
    for (let headline of this.headlines) {
        if (headline.id === id) {
            callback(headline);
            return;
        }
    }
    callback(null);
};


HeadlineService.prototype.deleteHeadline = function (id, callback) {
    let headlineDao = this.app.get("headlineDao");
    headlineDao.deleteHeadline(id, result => {
        if(!result || result.ok != 1) {
            callback(null);
            return;
        }
        let headlines = [];
        for(let headline of this.headlines) {
            if(headline.id !== id) {
                headlines.push(headline);
            }
        }
        this.headlines = headlines;
        callback(id);
    });
};

HeadlineService.prototype.tick = function () {
    let pushMessageService = this.app.get("pushMessageService");
    logger.info(`${JSON.stringify(this.headlines)}`);
    for(let headline of this.headlines) {
        let now = DateUtil.nowMS();
        if (now < headline.startTime || now > headline.endTime) {
            continue;
        }
        if (headline.isExpired(now)) {
            headline.lastTick = now;
            pushMessageService.broadcast("onBroadcastHeadline", headline.toSimpleJSON());
            logger.info(`Headline tick ${JSON.stringify(headline.toSimpleJSON())}`);
        }
    }
};

HeadlineService.prototype.serializeHeadlines = function (headlines) {
    let serializeHeadlines = [];
    for(let headline of headlines) {
        serializeHeadlines.push(headline.toJSON());
    }
    return serializeHeadlines;
};

module.exports.create = function (app) {
    return new HeadlineService(app);
};


